from ..base import base
from flask import request, jsonify, send_file
from flask_login import login_required
from .. import permission
import requests
from docx import Document
import tempfile
import time
import logging
import json  # 新增json模块导入

logger = logging.getLogger(__name__)

# 添加千帆配置项(应用监测分析指标问数Agent)
QIANFAN_API_KEY = 'bce-v3/ALTAK-cuCd30vaGULHkQUqasKCu/199c6f1e520aacca5b10d94c282ec20e5f4cf2e7'
METRIC_APP_ID = '1eaddc53-0e12-4ac8-a4e2-1602fb9e230c'
# 添加千帆配置项(应用监测分析报告Agent)
REPORT_APP_ID = '27cf2f97-cc0c-427c-bafe-e43d596b6beb'

@base.route('/smart/monitor/generateReport', methods=['POST'])
@login_required
# @permission('smart:monitor:report')
def generate_report():
    """生成监测报告（风格与server()方法保持一致）"""
    try:
        # 获取并验证请求参数
        metrics = request.json.get('metrics', [])
        if not metrics:
            return jsonify(code=400, msg="参数错误：未选择监测指标")

        # 调用封装的API函数
        conversation_id = start_qianfan_conversation_api(METRIC_APP_ID)
        if conversation_id == -1:
            return jsonify(code=500, msg="智能会话创建失败")

        # 数据处理（使用真实会话ID）
        data = {
            'app_id':METRIC_APP_ID,
            'conversation_id': conversation_id,
            'metrics': metrics  # 保留原始指标数据
        }
        # 把指标问数结果汇总后，作为提示词，让大模型进行方案生成
        metricQuestions =  process_data(data)

        new_conversation_id = start_qianfan_conversation_api(REPORT_APP_ID)
        logger.error("new_conversation_id",new_conversation_id)
        # 调用千帆问答API（使用系统配置的APP_ID）
        response = qianfan_ask_api(
            REPORT_APP_ID,
            new_conversation_id,
            metricQuestions
        )
        return jsonify(
            code=200,
            msg="报告生成成功",
            timestamp=int(time.time()),
            data=response
        )
    except Exception as e:
        logger.exception("报告生成异常")
        return jsonify(code=500, msg=f"服务器内部错误：{str(e)}")

@base.route('/smart/monitor/exportReport', methods=['POST'])
@login_required
# @permission('smart:monitor:export')
def export_report():
    """导出Word报告（保持统一响应格式）"""
    try:
        content = request.json.get('content')
        if not content:
            return jsonify(code=400, msg="参数错误：缺少报告内容")

        # 生成临时文件
        temp_path = generate_word_file(content)
        
        # 发送文件（自动清理临时文件）
        return send_file(
            temp_path,
            as_attachment=True,
            attachment_filename=f"monitor_report_{time.strftime('%Y%m%d%H%M%S')}.docx",
            mimetype='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        )

    except Exception as e:
        logger.exception("报告导出异常")
        return jsonify(code=500, msg=f"文件生成失败：{str(e)}")

def generate_word_file(content):
    """生成Word文件工具方法"""
    doc = Document()
    
    # 标题样式
    doc.add_heading('应用监测分析报告', 0).alignment = 1  # 居中对齐
    
    # 基本信息
    doc.add_paragraph(f"生成时间：{time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 表格数据
    table = doc.add_table(rows=1, cols=3)
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '指标名称'
    hdr_cells[1].text = '当前值'
    hdr_cells[2].text = '正常范围'
    
    for item in content:
        row_cells = table.add_row().cells
        row_cells[0].text = item.get('name', '')
        row_cells[1].text = str(item.get('value', ''))
        row_cells[2].text = item.get('range', '')
    
    # 保存临时文件
    temp_path = f"{tempfile.gettempdir()}/report_{int(time.time())}.docx"
    doc.save(temp_path)
    return temp_path

def process_data(data):
    """数据处理方法（实际业务实现）"""
    try:
        from ..models import DictData  # 引入字典数据模型
        results = []
        logger.error("指标数据是：%s", data)  # 新增调试日
        # 遍历每个指标（使用实际数据库查询）
        for metric in data.get('metrics', []):
            record = DictData.query.filter_by(
                dict_type='monitor_metric',
                dict_value=str(metric),  
                status=0  # 状态正常
            ).first()
            
            if record:
                logger.error("记录：%s,%s,%s", record.dict_value,record.dict_label,record.remark)  # 新增调试日                
                # 使用备注字段或字典标签作为问题内容
                question_content = record.remark if record.remark else record.dict_label
                
                # 调用千帆问答API（使用系统配置的APP_ID）
                questioncontent = qianfan_ask_api(
                    data['app_id'],
                    data['conversation_id'],
                    question_content
                )
                logger.error("response:::",questioncontent)
                # 收集结果（使用字典数据模型字段）
                results.append({
                    'metric': metric,
                    'metric_name': record.dict_label,
                    'question': questioncontent
                })
           
        return json.dumps(results, ensure_ascii=False)
    except Exception as e:
        logger.error(f"数据处理异常: {str(e)}", exc_info=True)
        return json.dumps({"error": str(e)}, ensure_ascii=False)

def start_qianfan_conversation_api(APP_ID):
    """调用千帆API获取会话ID"""
    try:
        url = "https://qianfan.baidubce.com/v2/app/conversation"
        payload = json.dumps({
            "app_id": f'{APP_ID}' # 使用配置项
        }, ensure_ascii=False)

        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {QIANFAN_API_KEY}'  # 使用配置项
        }
        logger.error("API请求头信息：%s", str(headers))  # 新增调试日
        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
        # response.raise_for_status()
        
        # 处理正常响应
        response_data = response.json()
        if 'conversation_id' in response_data:
            logger.error("conversation_id %s", response_data['conversation_id'])  # 新增调试日
            return response_data['conversation_id']
        # 处理业务异常
        logger.error(f"千帆API业务异常: {response_data.get('message')}")
        return -1
    except requests.exceptions.RequestException as e:
        logger.error(f"千帆API请求失败: {str(e)}")
        return -1
    except Exception as e:
        logger.error(f"千帆API处理异常: {str(e)}")
        return -1

def qianfan_ask_api(appId,conversation_id,question):
    """调用千帆API获取会话ID"""
    try:
        url = "https://qianfan.baidubce.com/v2/app/conversation/runs"
        payload = json.dumps({
            "app_id": f'{appId}', # 使用配置项
            "conversation_id":f'{conversation_id}',
            "query":f'{question}',
            "stream":False
        }, ensure_ascii=False)

        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {QIANFAN_API_KEY}'  # 使用配置项
        }
        logger.info("千帆请求头信息：%s", str(headers))  # 新增调试日
        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))
        # response.raise_for_status()
        
        # 处理正常响应
        response_data = response.json()
        logger.error("response_data %s", str(response_data))  
        return response_data["answer"]
    except Exception as e:
        logger.error(f"千帆API处理异常: {str(e)}")
        return ""